package com.gjzhao.fmmall.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.gjzhao.fmmall.constant.ConstantInfo;
import com.gjzhao.fmmall.dao.ProductImgMapper;
import com.gjzhao.fmmall.dao.ProductMapper;
import com.gjzhao.fmmall.dao.ProductParamsMapper;
import com.gjzhao.fmmall.dao.ProductSkuMapper;
import com.gjzhao.fmmall.entity.Product;
import com.gjzhao.fmmall.entity.ProductImg;
import com.gjzhao.fmmall.entity.ProductParams;
import com.gjzhao.fmmall.entity.ProductSku;
import com.gjzhao.fmmall.service.ProductService;
import com.gjzhao.fmmall.vo.PageHelper;
import com.gjzhao.fmmall.vo.ProductVO;
import com.gjzhao.fmmall.vo.RespCode;
import com.gjzhao.fmmall.vo.RespResultVO;
import com.gjzhao.fmmall.vo.ResponseResultVO;
import com.gjzhao.fmmall.vo.elasticsearch.ProductForEs;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

/**
 * @Description: 商品 ServiceImpl
 * @Author: gjzhao
 * @Date Created in 2022-01-02 11:00 上午
 */
@Service
public class ProductServiceImpl implements ProductService {

    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductImgMapper productImgMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private ProductParamsMapper productParamsMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //字符串 <-> 对象/集合 相互转换可使用
    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 查询推荐商品列表
     *
     * @return
     */
    @Override
    public ResponseResultVO listRecommendsProduct() {
        List<Product> products = productMapper.selectRecommendProductList();
        ResponseResultVO resultVO = new ResponseResultVO(RespCode.SUCCESS.getCode(), "success", products);
        return resultVO;
    }

    /**
     * 获取该分类下的排名前六的商品信息
     *
     * @return
     */
    @Override
    public ResponseResultVO listCategoryProduct(String categoryId) {

        if (StrUtil.isBlank(categoryId)) {
            return new ResponseResultVO(RespCode.FAILED.getCode(), "fail", null);
        } else {
            List<ProductVO> products = productMapper.selectTop6ByCategory(categoryId);
            return new ResponseResultVO(RespCode.SUCCESS.getCode(), "success", products);
        }
    }

    /**
     * 查询商品基本信息
     *
     * @param productId
     * @return
     */
    //@Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResponseResultVO listProductBasicInfo(String productId) {

        if (StrUtil.isBlank(productId)) {
            return new ResponseResultVO(RespCode.FAILED.getCode(), "查询商品id不能为空", null);
        } else {
            //商品基本信息
            Example example = new Example(Product.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("productId", productId);
            criteria.andEqualTo("productStatus", 1);//上架商品
            List<Product> products = productMapper.selectByExample(example);

            if (CollectionUtil.isEmpty(products)) {
                return new ResponseResultVO(RespCode.FAILED.getCode(), "所要查询的商品不存在", null);
            } else {
                //商品图片信息
                Example example1 = new Example(ProductImg.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("itemId", productId);
                List<ProductImg> productImgs = productImgMapper.selectByExample(example1);

                //商品套餐信息
                Example example2 = new Example(ProductSku.class);
                Example.Criteria criteria2 = example2.createCriteria();
                criteria2.andEqualTo("productId", productId);
                criteria2.andEqualTo("status", 1);//启用状态
                List<ProductSku> productSkus = productSkuMapper.selectByExample(example2);

                //封装需要返回的商品信息
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("product", products.get(0));
                map.put("productImgs", productImgs);
                map.put("productSkus", productSkus);

                return new ResponseResultVO(RespCode.FAILED.getCode(), "success", map);
            }
        }
    }


    /**
     * 查询商品基本信息(先从redis缓存中查询商品信息，没有再从数据库查找)
     *
     * @param productId
     * @return
     */
    @Override
    public RespResultVO listProductBasicInfoByRedis(String productId) {

        if (StrUtil.isBlank(productId)) {
            logger.info("-----参数校验 failed:{}------", productId);
            return RespResultVO.validateFailed();
        }

        // 1.先从redis查询商品信息:
        // 商品数据：{...}
        String productStr = (String) stringRedisTemplate.boundHashOps("products").get(productId);

        if (StrUtil.isNotBlank(productStr)) {
            //1.1 如果redis中存在商品信息
            logger.info("-----当前商品id:{},在redis中存在商品信息------", productId);

            //1.1.1 商品基本信息  将商品信息字符串转化为对象: {...} -> Product
            Product product = JSONUtil.toBean(productStr, Product.class);

            //1.1.2 商品图片信息 将商品图片信息字符串转化为集合对象： [{},{},{}...] -> List<ProductImg>
            String productImgsStr = (String) stringRedisTemplate.boundHashOps("productImgs").get(productId);
            JSONArray jsonArray1 = JSONUtil.parseArray(productImgsStr);
            List<ProductImg> productImgsList = JSONUtil.toList(jsonArray1, ProductImg.class);


            //1.1.3 商品套餐信息 讲商品套餐信息字符串转化为对象: [{},{},{}...] -> List<ProductSku>
            String productSkuStr = (String) stringRedisTemplate.boundHashOps("productSkus").get(productId);
            JSONArray jsonArray2 = JSONUtil.parseArray(productSkuStr);
            List<ProductSku> productSkuList = JSONUtil.toList(jsonArray2, ProductSku.class);

            //封装返回对象
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("product", product);
            map.put("productImgs", productImgsList);
            map.put("productSkus", productSkuList);

            logger.info("--------从redis中查询到商品信息:{}------", map);

            return RespResultVO.success(map);
        } else {
            //1.2 redis中不存在商品信息，先从数据库查询商品信息
            logger.info("-----当前商品:{},在redis中不存在商品基本信息，需要从数据库查询-----", productId);
            //1.2.1 商品基本信息
            Example example = new Example(Product.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("productId", productId);
            criteria.andEqualTo("productStatus", 1);
            List<Product> products = productMapper.selectByExample(example);

            //1.3 判断当前商品id是否存在商品
            if (CollectionUtil.isNotEmpty(products)) {
                //1.3.1 如果查询出商品信息，先缓存到redis
                // 基本信息: 一个商品id对应只有一个商品，放对象进去即可
                String product = JSONUtil.toJsonStr(products.get(0));

                stringRedisTemplate.boundHashOps("products").put(productId, product);
                logger.info("-----缓存商品基本信息,success:{}", product);

                // 商品图片信息：List<ProductImg> -> [{},{}..]
                Example example1 = new Example(ProductImg.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("itemId", productId);
                List<ProductImg> productImgs = productImgMapper.selectByExample(example1);
                String productImgsStr = JSONUtil.toJsonStr(productImgs);
                stringRedisTemplate.boundHashOps("productImgs").put(productId, productImgsStr);
                logger.info("-----缓存商品图片信息,success:{}", productImgsStr);

                //商品套餐信息
                Example example2 = new Example(ProductSku.class);
                Example.Criteria criteria2 = example2.createCriteria();
                criteria2.andEqualTo("productId", productId);
                criteria2.andEqualTo("status", 1);//启用状态
                List<ProductSku> productSkus = productSkuMapper.selectByExample(example2);
                String productSkuStr = JSONUtil.toJsonStr(productSkus);
                stringRedisTemplate.boundHashOps("productSkus").put(productId, productSkuStr);
                logger.info("-----缓存商品套餐信息,success:{}", productSkuStr);

                //封装需要返回的商品信息
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("product", products.get(0));
                map.put("productImgs", productImgs);
                map.put("productSkus", productSkus);

                logger.info("-----缓存商品信息完成,success:{}", map);
                return RespResultVO.success(map);
            } else {
                //1.3.2 如果未查询到商品，则查询数据为空
                logger.info("-----当前商品:{}，未查询到商品信息", productId);
                return RespResultVO.success("未查询到商品信息");
            }
        }
    }

    /**
     * 查询商品参数信息
     *
     * @param productId
     * @return
     */
    @Override
    public ResponseResultVO listProductParams(String productId) {

        //商品参数信息
        Example example = new Example(ProductParams.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productId", productId);
        List<ProductParams> productParams = productParamsMapper.selectByExample(example);

        if (CollectionUtil.isEmpty(productParams)) {
            return new ResponseResultVO(RespCode.FAILED.getCode(), "此商品可能为是三无产品", null);
        } else {
            return new ResponseResultVO(RespCode.SUCCESS.getCode(), "success", productParams.get(0));
        }
    }


    /**
     * 根据三级分类获取指定分页条件下的商品信息
     *
     * @param categoryId
     * @param pageNum
     * @param limit
     * @return
     */
    @Override
    public ResponseResultVO listProductByCategory(String categoryId, int pageNum, int limit) {

        if (StrUtil.isBlank(categoryId)) {
            return new ResponseResultVO(RespCode.FAILED.getCode(), "三级分类id不能为空", null);
        } else {
            //获取总数
            Example example = new Example(Product.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("categoryId", categoryId);
            int count = productMapper.selectCountByExample(example);

            //获取页数:如果不能够按照指定的条数分完，则还需要单独加一页
            int pageCount = count % limit == 0 ? count / limit : count / limit + 1;

            //计算起始条数
            int start = (pageNum - 1) * limit;

            //查询数据
            List<ProductVO> productVOList = productMapper.selectProductByCategoryId(categoryId, start, limit);


            //todo java8List转map的使用 可使用Stream流将List进行转换: 一个商品id对应一个商品图片列表
            Map<String, List<ProductImg>> listMap = productVOList.stream()
                                                                 .collect(Collectors.toMap(p -> p.getProductId(), p -> p.getImgs() != null ? p.getImgs() : new ArrayList<ProductImg>()));
            for (ProductVO p : productVOList) {
                logger.info("----当前商品id:{},对应的图片列表:{}----", p.getProductId(), listMap.get(p.getProductId()));
            }


            //封装分页对象
            PageHelper<ProductVO> pageHelper = new PageHelper<>();
            pageHelper.setCount(count);
            pageHelper.setCurrentPageNum(pageNum);
            pageHelper.setLimit(limit);
            pageHelper.setPageCount(pageCount);
            pageHelper.setList(productVOList);

            if (CollectionUtil.isEmpty(productVOList)) {
                return new ResponseResultVO(RespCode.SUCCESS.getCode(), "该三级分类下暂时还没有商品", null);
            } else {
                return new ResponseResultVO(RespCode.SUCCESS.getCode(), "success", pageHelper);
            }
        }
    }

    /**
     * 根据分类id获取该跟分类下的所有商品信息
     *
     * @param categoryId
     * @return
     */
    @Override
    public ResponseResultVO listBrandsByCategory(Integer categoryId) {
        List<String> brands = productMapper.selectBrandByCategoryId(categoryId);
        return new ResponseResultVO(RespCode.SUCCESS.getCode(), "success", brands);
    }

    @Override
    public ResponseResultVO searchProductByKeyword(String keyword, int pageNum, int limit) {

        //tips:给关键词加上模糊匹配符
        keyword = "%" + keyword + "%";

        //获取总数
        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("productName", keyword);
        int count = productMapper.selectCountByExample(example);

        //获取页数:如果不能够按照指定的条数分完，则还需要单独加一页
        int pageCount = count % limit == 0 ? count / limit : count / limit + 1;

        //计算起始条数
        int start = (pageNum - 1) * limit;

        //根据关键词查询商品信息
        List<ProductVO> productVOList = productMapper.selectProductByKeyword(keyword, start, limit);

        //封装分页对象
        PageHelper<ProductVO> pageHelper = new PageHelper<>();
        pageHelper.setCount(count);
        pageHelper.setCurrentPageNum(pageNum);
        pageHelper.setLimit(limit);
        pageHelper.setPageCount(pageCount);
        pageHelper.setList(productVOList);

        if (CollectionUtil.isEmpty(productVOList)) {
            return new ResponseResultVO(RespCode.SUCCESS.getCode(), "没有商品信息", null);
        } else {
            return new ResponseResultVO(RespCode.SUCCESS.getCode(), "success", pageHelper);
        }
    }

    /**
     * 根据关键词搜索商品信息(elasticsearch方式)
     *
     * @param keyword
     * @param pageNum
     * @param limit
     * @return
     */
    @Override
    public RespResultVO searchProductByKeywordByEs(String keyword, int pageNum, int limit) {

        //使用pageHelper进行分页查询
        com.github.pagehelper.PageHelper.startPage(pageNum, limit);

        try {
            //可以匹配的字段
            String name = "productName";
            String des = "productSkuName";
            //需要高亮的字段
            String highlightField1 = "productName";
            String highlightField2 = "productSkuName";

            //开始位置
            //int start = (pageNum - 1) * limit;

            //构造搜索条件对象
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //searchSourceBuilder.from(start); //开始位置 将所有击中的数据查询出来使用pagehelper插件进行分页
            //searchSourceBuilder.size(limit); //条数
            //searchSourceBuilder.query(QueryBuilders.matchQuery("name",keyword)); //单字段匹配
            searchSourceBuilder.query(QueryBuilders.multiMatchQuery(keyword, name, des)); //多字段匹配

            logger.info("----查询条件对象：{}---", searchSourceBuilder.toString());

            //构造响应结果高亮对象
            HighlightBuilder highlightBuilder = new HighlightBuilder();

            //需要高亮的字段
            HighlightBuilder.Field field1 = new HighlightBuilder.Field(highlightField1);
            HighlightBuilder.Field field2 = new HighlightBuilder.Field(highlightField2);
            field1.highlighterType("unified");
            field2.highlighterType("unified");

            //高亮的样式
            highlightBuilder.field(field1);
            highlightBuilder.field(field2);
            highlightBuilder.preTags("<label style='color:red'>");
            highlightBuilder.postTags("</label>");

            logger.info("-----结果高亮对象:{}----", highlightBuilder);
            searchSourceBuilder.highlighter(highlightBuilder);

            SearchRequest searchRequest = new SearchRequest(ConstantInfo.ELASTICSEARCH_PRODUCTS_INDEX_NAME);
            searchRequest.source(searchSourceBuilder);//搜索对象
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //击中的数据
            SearchHits hits = searchResponse.getHits(); //第一个hits包含：total、max_score、hits，具体每条数据在第二个hits中
            int count = (int) hits.getTotalHits().value;
            logger.info("---击中的条数：{},击中的最大分数：{}", count, hits.getMaxScore());

            for (SearchHit hit : hits.getHits()) {
                logger.info("----高亮的字段：{}", hit.getHighlightFields());
            }

            //封装响应的结果数据
            Iterator<SearchHit> iterator = hits.iterator();
            List<ProductForEs> list = new ArrayList<ProductForEs>();
            while (iterator.hasNext()) {
                SearchHit searchHit = iterator.next();
                //获取击中的数据
                String sourceAsString = searchHit.getSourceAsString();
                ProductForEs productForEs = JSONUtil.toBean(sourceAsString, ProductForEs.class);

                //替换高亮字段
                //1.更换productName字段
                HighlightField highlightFieldObj1 = searchHit.getHighlightFields().get("productName");
                if (highlightFieldObj1 != null) {
                    //可能击中name字段中多个，使用数组进行存放的，将其转化为字符串
                    //结果是一个数组，转化为字符串时，前后又一个'[]'，用空白字符串将其替换掉
                    String str = Arrays.toString(highlightFieldObj1.getFragments());
                    String str2 = StrUtil.replace(str, "[", "");
                    String str3 = StrUtil.replace(str2, "]", "");
                    //设置为高亮的字符串
                    productForEs.setProductName(str3);
                }
                //2.更换productSkuName字段
                HighlightField highlightFieldObj2 = searchHit.getHighlightFields().get("productSkuName");
                if (highlightFieldObj2 != null) {
                    //可能击中name字段中多个，使用数组进行存放的，将其转化为字符串
                    String str = Arrays.toString(highlightFieldObj2.getFragments());
                    String str2 = StrUtil.replace(str, "[", "");
                    String str3 = StrUtil.replace(str2, "]", "");
                    //设置为高亮的字符串
                    productForEs.setProductSkuName(str3);
                }
                list.add(productForEs);
            }

            logger.info("---最终查询结果：{}", list);

            //封装分页对象
            /*
            PageHelper pageHelper = new PageHelper();
            pageHelper.setCount(count);
            pageHelper.setList(list);
            pageHelper.setPageCount(count);
            pageHelper.setLimit(limit);
            pageHelper.setCurrentPageNum(pageNum);
             */

            //使用pagehelper插件，获取分页信息(总数/分页数/当前页)
            PageInfo<ProductForEs> pageInfo = new PageInfo<>(list);

            logger.info("---响应给前端的分页对象：{}", pageInfo);

            return RespResultVO.success(pageInfo);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return RespResultVO.failed("发生异常，查询失败");
    }

    /**
     * 根据关键词查询出来的商品的所有品牌信息
     *
     * @param keyword
     * @return
     */
    @Override
    public ResponseResultVO listBrandsByKeyword(String keyword) {

        //给关键词加上模糊匹配符
        keyword = "%" + keyword + "%";

        List<String> brands = productMapper.selectBrandsByKeyword(keyword);

        return new ResponseResultVO(RespCode.SUCCESS.getCode(), "success", brands);
    }

    /**
     * 初始化商品信息到es中
     *
     * @return
     */
    @Override
    @Transactional
    public RespResultVO initProductsIntoEs() {

        //1.查询商品信息
        List<ProductVO> productVOS = productMapper.selectAllProducts();
        logger.info("----从数据库查询到所有商品信息:{}----", productVOS);

        if (CollectionUtil.isEmpty(productVOS)) {
            return RespResultVO.failed("数据库不存在商品数据");
        }

        try {
            //2.将商品信息写入到es中
            //2.1 es中创建索引
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(ConstantInfo.ELASTICSEARCH_PRODUCTS_INDEX_NAME);
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices()
                                                                         .create(createIndexRequest, RequestOptions.DEFAULT);
            boolean acknowledged = createIndexResponse.isAcknowledged();
            logger.info("----es创建索引[fmmall_products_index],结果:{}----", acknowledged);

            if (acknowledged) {

                logger.info("----创建索引成功，开始向es中添加文档数据---");

                for (ProductVO productVO : productVOS) {

                    //2.2 封装要存储的数据对象：只有前端需要的数据字段才放到es中去
                    ProductForEs productForEs = new ProductForEs();
                    productForEs.setProductId(productVO.getProductId());
                    productForEs.setProductName(productVO.getProductName());
                    productForEs.setSoldNum(productVO.getSoldNum());

                    //将skus中数据取出来放在将要存储的对象中
                    List<ProductSku> skus = productVO.getSkus();
                    if (CollectionUtil.isNotEmpty(skus)) {

                        String skuName = skus.get(0).getSkuName() != null ? skus.get(0).getSkuName() : "";
                        Integer sellPrice = skus.get(0).getSellPrice() != null ? skus.get(0).getSellPrice() : 0;
                        String skuImg = skus.get(0).getSkuImg() != null ? skus.get(0).getSkuImg() : "";

                        productForEs.setProductSkuName(skuName);
                        productForEs.setProductSkuPrice(sellPrice);
                        productForEs.setProductImg(skuImg);
                    }

                    logger.info("----需要添加的数据对象：{}----", productForEs);

                    //2.3 将封装的文档数据存放在es中
                    String productStr = JSONUtil.toJsonStr(productForEs);

                    IndexRequest indexRequest = new IndexRequest(ConstantInfo.ELASTICSEARCH_PRODUCTS_INDEX_NAME);
                    indexRequest.id(productForEs.getProductId());//id
                    indexRequest.source(productStr, XContentType.JSON);//数据
                    IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

                    logger.info("-----向es添加文档的结果：{}----", indexResponse.getResult());

                }

                logger.info("----所有数据同步添加到es完成----");
            }
            return RespResultVO.success();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return RespResultVO.failed("同步数据到es失败");
    }


    /**
     * 添加商品(需要同步数据到es中)
     *
     * @param product
     * @return
     */
    @Override
    @Transactional
    public RespResultVO insertProduct(Product product) {

        try {
            //todo 1.添加数据到数据库

            //2.同步添加到es中
            // 2.1 查看索引是否存在
            GetIndexRequest getIndexRequest = new GetIndexRequest(ConstantInfo.ELASTICSEARCH_PRODUCTS_INDEX_NAME);
            GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
            if (getIndexResponse == null) {
                // 2.1.1 创建索引
                CreateIndexRequest createIndexRequest = new CreateIndexRequest(ConstantInfo.ELASTICSEARCH_PRODUCTS_INDEX_NAME);
                CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
                if (!createIndexResponse.isAcknowledged()) {
                    return RespResultVO.failed("执行es创建索引失败");
                }
            }
            // 2.2 添加数据文档
            IndexRequest indexRequest = new IndexRequest(ConstantInfo.ELASTICSEARCH_PRODUCTS_INDEX_NAME);
            //构造数据对象 todo 多条数据遍历添加
            ProductForEs productForEs = new ProductForEs("6", "apple", "...", 2, "64G", 5000);
            indexRequest.id(productForEs.getProductId());
            indexRequest.source(JSONUtil.toJsonStr(productForEs), XContentType.JSON);
            IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            if ("CREATED".equals(indexResponse.getResult().name())) {
                logger.info("----添加文档到es成功---");
            } else if ("UPDATED".equals(indexResponse.getResult().name())) {
                logger.info("----更新文档到es成功---");
            } else {
                logger.info("----添加到es失败---");
            }
            return RespResultVO.success();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return RespResultVO.failed("发生异常,添加失败");
    }


    /**
     * 根据商品id删除商品信息(需要同步删除es中商品信息)
     *
     * @param productId
     * @return
     */
    @Override
    @Transactional
    public RespResultVO deleteProduct(String productId) {

        try {
            //todo 1.删除数据库商品信息

            //2.同步删除es中商品信息
            DeleteRequest deleteRequest = new DeleteRequest(ConstantInfo.ELASTICSEARCH_PRODUCTS_INDEX_NAME);
            deleteRequest.id(productId);//指定需要删除的文档id
            DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            if ("DELETED".equals(deleteResponse.getResult().name())) {
                logger.info("---删除es中文档信息,success:{}----",deleteResponse.getResult().name());
            }
            return RespResultVO.success();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return RespResultVO.failed("发生异常,删除失败");
    }
}




